package com.excesys.exsecs.scada.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.excesys.exsecs.scada.entity.ScadaDevice;
import com.excesys.exsecs.scada.entity.ScadaFolder;
import com.excesys.exsecs.scada.entity.ScadaProperty;
import com.excesys.exsecs.scada.mapper.ScadaDeviceMapper;
import com.excesys.exsecs.scada.mapper.ScadaFolderMapper;
import com.excesys.exsecs.scada.mapper.ScadaPropertyMapper;
import com.excesys.exsecs.scada.service.ScadaPropertyService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 组态配置表
 *
 * @author tzh
 * @date 2024-05-10 16:01:26
 */
@Service
@RequiredArgsConstructor
public class ScadaPropertyServiceImpl extends ServiceImpl<ScadaPropertyMapper, ScadaProperty> implements ScadaPropertyService {
	private final ScadaDeviceMapper scadaDeviceMapper;
	private final ScadaPropertyMapper scadaPropertyMapper;
	private final ScadaFolderMapper scadaFolderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeDeep(Long[] ids) {
		if(ObjectUtils.isEmpty(ids)){
			return false;
		}
		List<ScadaDevice> scadaDevices = this.scadaDeviceMapper
				.selectList(Wrappers.<ScadaDevice>lambdaQuery().in(ScadaDevice::getScadaId, Arrays.asList(ids)));
		if(ObjectUtils.isNotEmpty(scadaDevices) || scadaDevices.size() > 0 ){
			return false;
		}
		//删除组态对应标签
		scadaFolderMapper.delete(Wrappers.<ScadaFolder>lambdaQuery().in(ScadaFolder::getScadaId, Arrays.asList(ids)));
		return this.removeBatchByIds(Arrays.asList(ids));
    }

	@Override
	public IPage selectAll(Page page, ScadaProperty scadaProperty, Integer bindFlag) {
		Map params = new HashMap<>();
		params.put("scadaName",scadaProperty.getScadaName());
		params.put("bindFlag",bindFlag);
		IPage<Map<String, String>> ipage = scadaPropertyMapper.selectAll(page, params);
		if (ObjectUtil.isNotEmpty(ipage) && CollectionUtils.isNotEmpty(ipage.getRecords())){
			ipage.getRecords().forEach(prop ->{
				prop.put("imageUrl",String.format("/admin/sys-file/oss/file?fileName=%s",prop.get("oimgName")));
				prop.put("fileUrl",String.format("/admin/sys-file/oss/file?fileName=%s",prop.get("ofileName")));
			});
		}
		return ipage;
	}
}